package org.carpediem.conman.client;

import org.apache.commons.cli.*;
import org.carpediem.schema.conman.*;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.StringWriter;
import java.util.Date;

/**
 * @author Mark Petrovic
 */
public class Base {
    protected CommandLine buildOptions(String[] args) throws ParseException {
        Options options = new Options();
        options.addOption("a", false, "attach new document to existing to contact");
        options.addOption("c", false, "create-contact");
        options.addOption("n", false, "add a note");
        options.addOption("q", false, "Lucene query");
        options.addOption("F", false, "create-firm");
        options.addOption("e", true, "email address of contact");
        options.addOption("d", true, "document to bind to contact (optional)");
        options.addOption("i", true, "entity id");
        options.addOption("m", true, "mime type of document");
        options.addOption("t", true, "note text");
        options.addOption("f", true, "Lucene field");
        options.addOption("s", true, "Lucene search criteria");
        options.addOption("u", true, "url");
        options.addOption("h", false, "help");
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);
        return cmd;
    }

    protected ContactInfo cInfo(long contactId, String documentFileName, String mimeType) {
        DocumentInfo dInfo = new DocumentInfo();
        dInfo.setOriginalName(documentFileName);
        dInfo.setMimetype(mimeType);

        BContactInfo bInfo = new BContactInfo();
        bInfo.setContactId(contactId);
        bInfo.getDocumentInfo().add(dInfo);

        ContactInfo cInfo = new ContactInfo();
        cInfo.setContact(bInfo);

        return cInfo;
    }

    protected ContactInfo cInfo(String emailAddress, String documentFileName, String mimeType) {
        DocumentInfo dInfo = new DocumentInfo();
        dInfo.setOriginalName(documentFileName);
        dInfo.setMimetype(mimeType);

        BContactInfo bInfo = new BContactInfo();
        bInfo.setEmailAddress(emailAddress);
        bInfo.getDocumentInfo().add(dInfo);

        ContactInfo cInfo = new ContactInfo();
        cInfo.setContact(bInfo);

        return cInfo;
    }

    protected NoteInfo nInfo(String note) {
        NoteInfo nInfo = new NoteInfo();
        BNoteInfo bInfo = new BNoteInfo();
        bInfo.setNote(note);
        nInfo.setNote(bInfo);
        return nInfo;
    }

    protected <T> String toXml(T instance) {
        StringWriter sWriter = new StringWriter();
        try {
            JAXBContext jc = JAXBContext.newInstance(instance.getClass());
            Marshaller m = jc.createMarshaller();
            m.marshal(instance, sWriter);
        } catch (JAXBException e) {
            e.printStackTrace();
        }

        return sWriter.toString();
    }

}
